'''
Created on Mar 25, 2013

@author: LONG HOANG GIANG
'''

import mechanize
import urllib
import HttpResponse
import gzip as _gzip
import cStringIO
from pyLib import getCacheDir, md5, CacheManager
from urllib import urlencode


class Http():
    
    @staticmethod
    def loadWeb(url, data={}, cached=True, referer='', cookiestr='', useragent='', sendajax=False):
        firefoxUserAgent = "Mozilla/5.0 (Windows NT 6.2; rv:20.0) Gecko/20100101 Firefox/20.0"
        opener = mechanize.build_opener(
                    mechanize.HTTPCookieProcessor, 
                    mechanize.HTTPRefererProcessor, 
                    mechanize.HTTPRedirectHandler)
        opener.addheaders = [("User-Agent", useragent if useragent != '' else firefoxUserAgent), 
                             ("Referer", referer),
                             ("Cookie", cookiestr)]
        if (sendajax):
            opener.addheaders.append(("X-Requested-With", "XMLHttpRequest"))
        cachedFile = getCacheDir() + md5(url + str(data))
        res = CacheManager.get(cachedFile)
        if res != None: return res
        mechanize.install_opener(opener)
        try:
            fp = mechanize.urlopen(url, urlencode(data)) if len(data.items()) == 0 else mechanize.urlopen(url)
        except:
            fp = urllib.urlopen(url, urlencode(data)) if len(data.itmes()) == 0 else urllib.urlopen(data)
        content = fp.read()
        info = fp.info()
        if (info.get('Content-Encoding', '') == 'gzip'):
            gzipper = _gzip.GzipFile(fileobj=cStringIO.StringIO(content))
            data = gzipper.read()
        res = HttpResponse(content)
        res.set(info, fp.getcode(), fp.geturl(), info.get('Set-Cookie', ''))
        fp.close()
        return res
        
        
        